package l.l.w.leetcode._204_CountPrimes;

import java.util.Arrays;
import java.util.BitSet;

/**
 * Created by llw on 2018/5/17/0017.
 */
public class Solution {

    /**
     * int cnt=0;
     memset(vis,0,sizeof(vis));
     for(int i=2;i<n;i++)
     {
     if(!vis[i])
     prime[cnt++]=i;
     for(int j=0;j<cnt&&i*prime[j]<n;j++)
     {
     vis[i*prime[j]]=1;
     if(i%prime[j]==0)//关键
     break;
     * @param n
     * @return
     */
    public int countPrimes1(int n) {
        int count = 0;
        boolean[] prime = new boolean[n];
        int[] record = new int[n];
        for(int i = 2; i < n; ++i){
            if(!prime[i]){
                record[count++] = i;
            }
            for(int j = 0; j < count && i * record[j] < n; ++j){
                prime[i * record[j]] = true;
                if( i % record[j] == 0) break;
            }
        }
        System.out.println(Arrays.toString(record));
        return count;
    }
    /**
     * 埃拉特斯特尼筛法
     * @param n
     * @return
     */
    public int countPrimes(int n) {
        BitSet bitSet = new BitSet(n);
        for(int i = 0; i < n; ++i){
            bitSet.set(i, true);
        }
        bitSet.set(0,false);
        bitSet.set(1,false);
        for(int i = 2; i <= Math.sqrt(n); ++i){
            if(bitSet.get(i))
            for(int j = i; i * j < n; ++j){
                bitSet.set(i * j, false);
            }
        }

        int res = bitSet.cardinality();
        return res;
    }

    public static void main(String[] args) {
        int n = 20;
        int res = new Solution().countPrimes1(n);
        System.out.println(res);
    }
}
